package Com.aop.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 数据库工具类
 * */
public class DBUtils {
    static String Driver="com.mysql.jdbc.Driver";
    static String url="jdbc:mysql://localhost:3306/myschool";
    static String uname="root";
    static String pwd="123456";
    //创建一个小的容器来存储Connection
   public  static ThreadLocal<Connection> threadLocal=new ThreadLocal<Connection>();
    /**
     * 想使用jdbc事务去管理逻辑单元
     * 在jdbc中开启事务必须保证 多个语句的执行在同一个Connection
     * 因为事务的开启提交回滚的基于Connection
     *
     * */
    static Connection getcon(){
        Connection connection=threadLocal.get();
        try {
            if(connection==null){
                Class.forName(Driver);
                connection = DriverManager.getConnection(url, uname, pwd);
                threadLocal.set(connection);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return connection;
    }
    public  static int ExecuteUpdate(String sql,Object[] objects) throws SQLException {
        Connection connection=getcon();
        try {
            PreparedStatement ment = connection.prepareStatement(sql);

            if(objects!=null){
                for (int i = 0; i < objects.length; i++) {
                   ment.setObject(i+1,objects[i]);
                }
                return ment.executeUpdate();
            }


        } catch (SQLException e) {
          throw  e;
        }
return -1;
    }
    public  static  void setAutoCommit(boolean falg){
        try {
            getcon().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public  static  void commit(){
        try {
            getcon().commit();
            setAutoCommit(true);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public  static  void rollback(){
        try {
            getcon().rollback();
            setAutoCommit(true);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
